<template>
  <k-view class="rank-list-block">
    <k-view class="rank-list-title">
      <k-text class="rank-list-title-text">{{ rankTypeName }}排行榜</k-text>
      <k-text @click="goRankPage" class="rank-list-title-subtext">更多</k-text>
    </k-view>
    <k-view class="rank-list-content">
      <rank-table
        :themeType="'mobile-app-' + themeType"
        :data="data"
        :globalLoading="isLoading"
        :isShowNoData="isEmpty"
        :requestData="tableData"
        @click-row="clickRow"
        @tableSort="tableSort"
        :customSort="customSort"
      ></rank-table>
    </k-view>
  </k-view>
</template>

<script>
import Apis from '@king-fisher/apis';
import { tableHeaderData } from '@/config/tableHeader';
import { getRankingList } from '@/apis';
import { jumpByUrl, jumpToFenshi } from '@/utils';
import { sendClickStat } from '@/utils/stat';
import { INDEX_TAB_ID, PAGEID } from '@/config/stat';

export default {
  props: {
    themeType: {
      type: String,
      default: '',
    },
    activeTab: {
      type: Number,
      default: 1,
    },
    currentItem: {
      type: Object,
      default: () => {
        return {
          code: '',
          label: '',
          value: '',
        };
      },
    },
    stockCodes: {
      type: String,
      default: '',
      required: false,
    },
  },
  watch: {
    currentItem: {
      handler(val) {
        if (val.code) {
          this.getRankingListOverview();
        }
      },
      deep: true,
    },
  },
  data() {
    return {
      isLoading: false,
      data: tableHeaderData,
      tableData: [],
      originData: [],
      customSort: true,
      page_size: '9',
      page_num: '0',
      sort_field: 'composite_score',
      sort_way: 'desc',
    };
  },
  methods: {
    clickRow(row, column) {
      const stockIndex = this.originData.findIndex(item => item.code === row.stock_code);
      if (stockIndex !== -1) {
        const stockItem = this.originData[stockIndex];
        if (column.type === 'stock') {
          //跳转个股分时
          sendClickStat(
            `${PAGEID.INDEX}.${INDEX_TAB_ID[this.activeTab]}.list.stocks.${row.stock_code}.${
              stockIndex + 1
            }.click`
          );
          jumpToFenshi(row.stock_code, stockItem.market, stockItem.name);
        } else {
          //跳转个股诊断
          sendClickStat(
            `${PAGEID.INDEX}.${INDEX_TAB_ID[this.activeTab]}.list.bmidetails.${row.stock_code}.${
              stockIndex + 1
            }.click`
          );
          jumpByUrl({
            name: 'stock',
            query: {
              stockCode: row.stock_code,
              market: stockItem.market,
              stockName: row.stock_name,
            },
          });
        }
      }
    },
    async getRankingData(params, api, reload) {
      this.isLoading = true;
      let timer;
      const timeout = new Promise((resolve, reject) => {
        timer = setTimeout(() => {
          reject('请求超时!');
        }, 3000);
      });
      Promise.race([timeout, api(params)])
        .then(res => {
          if (res.status_code !== 0) {
            Apis.Toast.show('暂未查询到相关信息');
            return;
          }
          this.tableData = res.data.list?.map(item => {
            return {
              stock_name: item.name,
              stock_code: item.code,
              composite_score: item.composite_score.toFixed(2),
              nervous_score: item.nervous_score.toFixed(2),
              motor_score: item.motor_score.toFixed(2),
              secretion_score: item.secretion_score.toFixed(2),
              immune_score: item.immune_score.toFixed(2),
              respiratory_score: item.respiratory_score.toFixed(2),
              circulatory_score: item.circulatory_score.toFixed(2),
              urinary_score: item.urinary_score.toFixed(2),
              digesive_score: item.digesive_score.toFixed(2),
              reproductive_score: item.reproductive_score.toFixed(2),
              market: item.market,
            };
          });
          this.originData = res.data.list;
        })
        .finally(() => {
          this.isLoading = false;
          clearTimeout(timer);
        });
    },
    async getRankingListData(params) {
      this.getRankingData(params, getRankingList);
    },
    async getBlockRankingListData(params) {
      this.getRankingData(params, getRankingList);
    },
    getRankingListOverview() {
      const params: rank_params = {
        block_type: this.blockType,
        page_size: this.page_size,
        page_num: this.page_num,
        sort_field: this.sort_field,
        sort_mod: this.sort_way,
      };
      tableHeaderData[1].label = '股票名称';
      if (this.activeTab === 1) {
        this.getRankingListData(params);
      } else if (this.activeTab === 2) {
        params.stock_codes = this.stockCodes;
        this.getRankingListData(params);
      } else if (this.activeTab === 3) {
        //行业Tab，调用板块排行榜
        params.block_code = this.currentItem.code;
        this.getBlockRankingListData(params);
      } else if (this.activeTab === 4) {
        //板块Tab，调用板块排行榜
        params.block_code = this.currentItem.code;
        this.getBlockRankingListData(params);
      }
    },
    goRankPage() {
      if (this.activeTab === 3 || this.activeTab === 4) {
        //行业或地区
        sendClickStat(
          `${PAGEID.INDEX}.${INDEX_TAB_ID[this.activeTab]}.${this.currentItem.code}.list.more.click`
        );
        jumpByUrl(
          `regionrank?block_code=${this.currentItem.code}&block_type=${this.blockType}&block_name=${this.currentItem.label}`
        );
      } else {
        sendClickStat(`${PAGEID.INDEX}.${INDEX_TAB_ID[this.activeTab]}.list.more.click`);
        jumpByUrl({ name: 'rank', query: { activeTab: this.activeTab } });
      }
    },
    tableSort(key, sortWay) {
      const params: rank_params = {
        block_type: this.blockType,
        page_size: this.page_size,
        page_num: this.page_num,
        sort_field: key,
        sort_mod: sortWay,
      };
      tableHeaderData[1].label = '股票名称';
      if (this.activeTab === 1) {
        this.getRankingListData(params);
      } else if (this.activeTab === 2) {
        params.stock_codes = this.stockCodes;
        this.getRankingListData(params);
      } else if (this.activeTab === 3) {
        //行业Tab，调用板块排行榜
        params.block_code = this.currentItem.code;
        this.getBlockRankingListData(params);
      } else if (this.activeTab === 4) {
        //板块Tab，调用板块排行榜
        params.block_code = this.currentItem.code;
        this.getBlockRankingListData(params);
      }
      this.sort_field = key;
      this.sort_way = sortWay;
    },
    reload() {
      this.getRankingListOverview();
    },
  },
  mounted() {
    this.getRankingListOverview();
  },
  computed: {
    blockType() {
      const tabMapping = {
        1: 'all_market',
        2: 'stock',
        3: 'industry',
      };
      // 如果 activeTab 对应的值存在于 tabMapping 中，则返回该值；否则默认返回 'region'
      return tabMapping[this.activeTab] || 'region';
    },
    rankTypeName() {
      // 对于其他情况，使用对象映射来简化逻辑
      const tabMapping = {
        1: '健康度',
        2: '自选',
        3: this.currentItem.label,
        4: this.currentItem.label,
        // 可以在这里添加更多的映射关系，如果有的话
      };
      // 如果 activeTab 对应的值存在于 tabMapping 中，则返回该值；否则默认返回 '健康度'
      return tabMapping[this.activeTab] || '健康度';
    },
    isEmpty() {
      return this.tableData.length === 0;
    },
  },
};
</script>

<style lang="less">
.rank-list-block {
  width: 100%;
  background-color: #ffffff;
  border-radius: 16px;
  padding: 20px;
  .rank-list-title {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    background-image: url(../../assets/index/right_arrow.png);
    background-repeat: no-repeat;
    background-size: 14px 24px;
    background-position: 100% 36%;
    .rank-list-title-text {
      font-size: 36px;
      color: #262626;
      font-weight: 500;
      line-height: 50px;
    }
    .rank-list-title-subtext {
      color: rgba(0, 0, 0, 0.4);
      font-size: 28px;
      line-height: 50px;
      font-weight: 400;
      padding-right: 28px;
    }
  }
  .rank-list-content {
    margin-top: 14px;
  }
}
[theme-mode='black'] {
  .rank-list-block {
    background-color: #1c1c1c;
    .rank-list-title {
      background-image: url(../../assets/index/right_arrow_light.png);
    }
    .rank-list-title-text {
      color: rgba(255, 255, 255, 0.84);
    }
    .rank-list-title-subtext {
      color: rgba(255, 255, 255, 0.4);
    }
  }
}
.hxm-table {
  z-index: 0 !important;
}
</style>
